<template>
  <div class="page-content">
    <div class="form">
      <el-col :xs="24" :sm="24" :lg="24">
        <h1 class="title">设置logo图</h1>
        <el-upload
          class="upload-setting"
          drag
          :action="logodataUrl"
          :data="uploadData"
          :on-success="refresh"
          :before-upload="beforeUpload"
        >
          <img v-if="logoImageUrl" :src="logoImageUrl" width="180" />
          <div v-else>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，建议图片比例：<span>647*339</span>
            </div>
          </div>
        </el-upload>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="24">
        <h1 class="title">设置banner图</h1>
        <el-upload
          class="upload-setting"
          :action="bannerdataUrl"
          :on-preview="bannerhandlePreview"
          :on-remove="bannerhandleRemove"
          :file-list="bannerfileList"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，允许设置多张图片，建议图片比例：<span
              >1300*400</span
            >
          </div>
        </el-upload>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="24">
        <h1 class="title">设置门店图</h1>
        <el-upload
          class="mdupload-setting"
          :action="mddataUrl"
          :on-preview="mdhandlePreview"
          :on-remove="mdhandleRemove"
          :file-list="mdfileList"
          list-type="picture"
          accept="image/*"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，最多允许添加3张图片，建议图片比例：<span
              >900*400</span
            >
          </div>
        </el-upload>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <el-form :model="indexform" ref="indexform">
          <el-form-item prop="indexweb">
            <el-col :xs="24" :sm="24" :lg="24">
              <h1 class="title2">设置自定义主页 [ 例如：www.iqp168.com ]</h1>
              <el-input v-model="indexform.indexweb" placeholder="">
                <template slot="prepend">Http://</template>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item prop="businesshours">
            <el-col :xs="24" :sm="24" :lg="24">
              <h1 class="title2">设置营业时间</h1>
              <el-input v-model="indexform.businesshours" placeholder="" />
            </el-col>
          </el-form-item>
          <el-form-item prop="body">
            <el-col :xs="24" :sm="24" :lg="24">
              <h1 class="title2">设置公司简介</h1>
              <quill-editor
                class="editor"
                ref="quillEditor"
                v-model="indexform.body"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @ready="onEditorReady($event)"
              />
              <el-upload
                class="upload-demo"
                :action="dataUrl"
                :before-upload="beforeUpload"
                :data="uploadData"
                :headers="headers"
                :on-success="upScuccess"
                ref="upload"
                multiple
                style="display:none"
              >
                <el-button
                  type="primary"
                  id="imgInput"
                  v-loading.fullscreen.lock="fullscreenLoading"
                  element-loading-text="插入中,请稍候"
                >
                  点击上传
                </el-button>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col>
        <el-button type="danger" icon="el-icon-check" @click="saveData"
          >保存</el-button
        >
        <el-button type="primary" icon="el-icon-view" @click="goindex"
          >浏览</el-button
        >
      </el-col>
    </div>
  </div>
</template>

<script>
import { indexWebApi } from "@/api/cardApi";
import { delbannerimgApi } from "@/api/cardApi";
import { delmdimgApi } from "@/api/cardApi";
import { IndexManagerApi } from "@/api/cardApi";
import { baseUrl } from "@/utils/config";
import { quillEditor, Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "@styles/quill.scss";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import ImageResize from "quill-image-resize-module";

Quill.register("modules/ImageExtend", ImageExtend);
Quill.register("modules/ImageResize", ImageResize);
export default {
  inject: ["reload"],
  components: {
    quillEditor
  },
  data() {
    return {
      uploadData: {
        guestcode: "",
        gscode: ""
      },
      content: "",
      headers: {
        Authorization: ""
      },
      indexform: {
        indexweb: "",
        businesshours: "",
        body: ""
      },
      dataUrl: baseUrl + "/api/Card/upload_Imgurl",
      logoImageUrl: "",
      httpimgUrl: "http://img.inheart.cn",
      logodataUrl: baseUrl + "/api/Card/indexupload_Imgurl",
      bannerdataUrl: baseUrl + "/api/Card/indexupload_Imgurl",
      mddataUrl: baseUrl + "/api/Card/indexupload_Imgurl",
      value: "",
      fullscreenLoading: false,
      bannerfileList: [],
      mdfileList: [],
      editorOption: {
        modules: {
          ImageResize: {
            //调整大小组件。
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
          ImageExtend: {
            // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
            loading: true, // 可选参数 是否显示上传进度和提示语
            placeholder: "",
            name: "img", // 图片参数名
            size: 500, // 可选参数 图片大小，单位为M，1M = 1024kb
            methods: "POST", // 可选参数 图片上传方式  默认为post
            accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon",
            action: this.dataUrl, // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
            // 则 return res.data.url
            response: res => {
              let imgurl = "http://img.inheart.cn";
              return imgurl + res.statusText;
            },
            headers: xhr => {
              xhr.setRequestHeader("contentType", "application/json");
            }, // 可选参数 设置请求头部
            sizeError: () => {}, // 图片超过大小的回调
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 上传失败触发的事件
            success: () => {}, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {} // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            // 如果不上传图片到服务器，此处不必配置
            container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
            handlers: {
              image: function() {
                // 劫持原来的图片点击按钮事件
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      }
    };
  },
  mounted() {
    this.indexWebData();
  },
  methods: {
    indexWebData() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      indexWebApi({
        guestcode: guestcode,
        gscode: gscode,
        username: username,
        userid: userid,
        menuename: "IndexSetting",
        menucname: "主页设置",
        logintype: logintype,
        posttype: posttype,
        op_type: "查询"
      }).then(res => {
        if (res.logoimg != "") {
          this.logoImageUrl = this.httpimgUrl + res.logoimg;
        }
        if (res.bannerimg != "") {
          for (var i = 0; i < res.bannerimg.split(",").length; i++) {
            this.bannerfileList.push({
              name: "",
              url: this.httpimgUrl + res.bannerimg.split(",")[i] + "&original=1"
            });
          }
        }
        if (res.mdimg != "") {
          for (var j = 0; j < res.mdimg.split(",").length; j++) {
            this.mdfileList.push({
              name: "",
              url: this.httpimgUrl + res.mdimg.split(",")[j] + "&original=1"
            });
          }
        }
        this.indexform = res;
        this.logodataUrl =
          this.logodataUrl +
          "?imgtype=logoimg&guestcode=" +
          guestcode +
          "&gscode=" +
          gscode;
        this.bannerdataUrl =
          this.bannerdataUrl +
          "?imgtype=bannerimg&guestcode=" +
          guestcode +
          "&gscode=" +
          gscode;
        this.mddataUrl =
          this.mddataUrl +
          "?imgtype=mdimg&guestcode=" +
          guestcode +
          "&gscode=" +
          gscode;
        this.dataUrl =
          this.dataUrl + "?guestcode=" + guestcode + "&gscode=" + gscode;
        let quill = this.$refs.quillEditor.quill;
        // 监听工具栏图片点击
        quill.getModule("toolbar").addHandler("image", this.imgHandler);
      });
    },
    bannerhandleRemove(file, fileList) {
      let bannerUrl = "";
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      fileList.forEach(element => {
        bannerUrl +=
          element.url.replace(this.httpimgUrl, "").replace("&original=1", "") +
          ",";
      });
      delbannerimgApi({
        guestcode: guestcode,
        gscode: gscode,
        bannerimg: bannerUrl.slice(0, bannerUrl.length - 1)
      }).then(res => {
        if (res.code == "0") {
          this.$message.success(res.msg);
        }
      });
    },
    bannerhandlePreview(file) {
      console.log(file);
    },
    mdhandleRemove(file, fileList) {
      let mdUrl = "";
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      fileList.forEach(element => {
        mdUrl +=
          element.url.replace(this.httpimgUrl, "").replace("&original=1", "") +
          ",";
      });
      delmdimgApi({
        guestcode: guestcode,
        gscode: gscode,
        mdimg: mdUrl.slice(0, mdUrl.length - 1)
      }).then(res => {
        if (res.code == "0") {
          this.$message.success(res.msg);
        }
      });
    },
    mdhandlePreview(file) {
      console.log(file);
    },
    imgHandler(state) {
      let quill = this.$refs.quillEditor.quill;
      this.addRange = quill.getSelection();
      if (state) {
        let fileInput = document.getElementById("imgInput");
        fileInput.click(); // 加一个触发事件
      }
      this.uploadType = "image";
    },
    submit() {},
    beforeUpload(file) {
      this.uploadData.guestcode = JSON.parse(
        JSON.stringify(this.$store.state.user.user.info)
      ).reguserno;
      this.uploadData.gscode = JSON.parse(
        JSON.stringify(this.$store.state.user.user.info)
      ).gscode;
    },
    upScuccess(e) {
      let path = e.statusText;
      let url = "http://img.inheart.cn" + path;
      let quill = this.$refs.quillEditor.quill;
      let selection = quill.getSelection();

      // 获取光标的位置
      let cursorIndex = selection ? selection.index : 0;
      // 插入图片到编辑器
      quill.insertEmbed(cursorIndex, "image", url);
      // 调整光标到最后
      quill.setSelection(cursorIndex + 1);
    },
    onEditorBlur(quill) {}, // 失去焦点事件
    onEditorFocus(quill) {}, // 获得焦点事件
    onEditorReady(quill) {}, // 内容改变事件
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 转码
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    saveData() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      IndexManagerApi({
        guestcode: guestcode,
        gscode: gscode,
        indexweb: this.indexform.indexweb,
        businesshours: this.indexform.businesshours,
        body: this.indexform.body,
        username: username,
        userid: userid,
        menuename: "IndexSetting",
        menucname: "主页设置",
        logintype: logintype,
        posttype: posttype,
        op_type: "保存",
        note: JSON.stringify(this.indexform)
      }).then(res => {
        if (res.code == "0") {
          this.$message.success(res.msg);
          this.refresh();
        }
      });
    },
    goindex() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let cardno = userdata.cardno;
      window.open(baseUrl + "/" + cardno);
    },
    refresh() {
      this.reload();
    }
  },
  computed: {
    editor() {
      return this.$refs.quillEditor.quill;
    }
  }
};
</script>

<style lang="scss" scoped>
.page-content {
  overflow: hidden;
  .title {
    font-size: 22px;
    font-weight: 500;
    padding-top: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }
  .title2 {
    font-size: 22px;
    font-weight: 500;
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .el-upload__tip span {
    color: #f56c6c;
  }
  .form {
    max-width: 100%;

    .upload-setting {
      margin-top: 10px;
    }

    .mdupload-setting {
      margin-top: 10px;
    }

    ::v-deep .el-upload--picture-card {
      width: 220px;
      height: 140px;
    }
  }
  ::v-deep .upload-setting .el-upload-list--picture .el-upload-list__item {
    width: 368px;
    height: 120px;
    float: left;
    margin-right: 10px;
  }
  ::v-deep
    .upload-setting
    .el-upload-list--picture
    .el-upload-list__item-thumbnail {
    width: 325px;
    height: 100px;
  }
  ::v-deep .mdupload-setting .el-upload-list--picture .el-upload-list__item {
    width: 338px;
    height: 220px;
    float: left;
    margin-right: 10px;
  }
  ::v-deep
    .mdupload-setting
    .el-upload-list--picture
    .el-upload-list__item-thumbnail {
    width: 300px;
    height: 133px;
    padding-top: 33px;
    padding-left: 5px;
  }

  @media only screen and (max-width: $device-ipad) {
    ::v-deep .upload-setting .el-upload-list--picture .el-upload-list__item {
      width: 100%;
      height: 120px;
    }
    ::v-deep
      .upload-setting
      .el-upload-list--picture
      .el-upload-list__item-thumbnail {
      width: 100%;
      height: 100px;
    }
    ::v-deep .mdupload-setting .el-upload-list--picture .el-upload-list__item {
      width: 100%;
      height: 220px;
    }
    ::v-deep
      .mdupload-setting
      .el-upload-list--picture
      .el-upload-list__item-thumbnail {
      width: 100%;
      height: 133px;
    }
    ::v-deep .el-upload-dragger {
      width: 100%;
    }
    ::v-deep .el-upload-dragger img {
      width: 50%;
    }
  }
}
</style>
